'use client'

import { useState, useEffect } from 'react'
import Link from 'next/link'
import { MegaphoneIcon, PencilSquareIcon, TrashIcon } from '@heroicons/react/24/outline'
import { useSession } from 'next-auth/react'
import Button from '@/components/ui/Button'

interface Announcement {
  id: string
  title: string
  content: string
  experimentId: string
  createdAt: string
  updatedAt: string
  experiment: {
    title: string
  }
}

interface AnnouncementListProps {
  experimentId?: string
  canManage?: boolean
  onAnnouncementAdded?: (announcement: Announcement) => void
}

export default function AnnouncementList({
  experimentId,
  canManage = false,
  onAnnouncementAdded,
}: AnnouncementListProps) {
  const { data: session } = useSession()
  const [announcements, setAnnouncements] = useState<Announcement[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')
  const [showForm, setShowForm] = useState(false)
  const [formData, setFormData] = useState({
    title: '',
    content: '',
  })

  // 获取公告列表
  const fetchAnnouncements = async () => {
    try {
      setLoading(true)
      const url = experimentId 
        ? `/api/announcements?experimentId=${experimentId}`
        : '/api/announcements'
      
      const response = await fetch(url)
      
      if (!response.ok) {
        throw new Error('获取公告失败')
      }
      
      const data = await response.json()
      setAnnouncements(data.announcements)
    } catch (err: any) {
      setError(err.message || '获取公告失败')
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    fetchAnnouncements()
  }, [experimentId])

  // 创建公告
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    
    if (!formData.title || !formData.content) {
      setError('请填写完整信息')
      return
    }
    
    try {
      const response = await fetch('/api/announcements', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          ...formData,
          experimentId,
        }),
      })
      
      if (!response.ok) {
        const data = await response.json()
        throw new Error(data.message || '创建公告失败')
      }
      
      const data = await response.json()
      
      // 重置表单
      setFormData({
        title: '',
        content: '',
      })
      setShowForm(false)
      
      // 更新公告列表
      if (onAnnouncementAdded) {
        onAnnouncementAdded(data.announcement)
      } else {
        setAnnouncements(prev => [data.announcement, ...prev])
      }
    } catch (err: any) {
      setError(err.message || '创建公告失败')
    }
  }

  // 删除公告
  const handleDelete = async (id: string) => {
    if (!confirm('确定要删除这个公告吗？')) {
      return
    }
    
    try {
      const response = await fetch(`/api/announcements/${id}`, {
        method: 'DELETE',
      })
      
      if (!response.ok) {
        const data = await response.json()
        throw new Error(data.message || '删除公告失败')
      }
      
      // 更新公告列表
      setAnnouncements(prev => prev.filter(item => item.id !== id))
    } catch (err: any) {
      setError(err.message || '删除公告失败')
    }
  }

  // 格式化日期显示
  const formatDate = (dateString: string) => {
    const date = new Date(dateString)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: 'numeric',
      day: 'numeric',
      hour: 'numeric',
      minute: 'numeric',
    })
  }

  const isTeacherOrAdmin = session?.user?.role === 'TEACHER' || session?.user?.role === 'ADMIN'

  return (
    <div className="space-y-6">
      {error && (
        <div className="rounded-md bg-red-50 p-4">
          <div className="text-sm text-red-700">{error}</div>
        </div>
      )}
      
      {isTeacherOrAdmin && experimentId && (
        <div className="flex justify-end">
          <Button
            onClick={() => setShowForm(!showForm)}
            variant={showForm ? 'secondary' : 'primary'}
          >
            {showForm ? '取消' : '发布公告'}
          </Button>
        </div>
      )}
      
      {showForm && experimentId && (
        <div className="bg-white p-6 rounded-lg shadow">
          <h3 className="text-lg font-medium text-gray-900 mb-4">发布新公告</h3>
          
          <form onSubmit={handleSubmit} className="space-y-4">
            <div>
              <label htmlFor="title" className="block text-sm font-medium text-gray-700">
                标题
              </label>
              <input
                type="text"
                id="title"
                value={formData.title}
                onChange={(e) => setFormData({ ...formData, title: e.target.value })}
                className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
                required
              />
            </div>
            
            <div>
              <label htmlFor="content" className="block text-sm font-medium text-gray-700">
                内容
              </label>
              <textarea
                id="content"
                value={formData.content}
                onChange={(e) => setFormData({ ...formData, content: e.target.value })}
                rows={4}
                className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm"
                required
              />
            </div>
            
            <div className="flex justify-end">
              <Button type="submit">发布公告</Button>
            </div>
          </form>
        </div>
      )}
      
      {loading ? (
        <div className="text-center py-4">加载中...</div>
      ) : announcements.length === 0 ? (
        <div className="text-center py-4 text-gray-500">暂无公告</div>
      ) : (
        <div className="bg-white overflow-hidden shadow rounded-lg">
          <ul className="divide-y divide-gray-200">
            {announcements.map((announcement) => (
              <li key={announcement.id} className="p-6">
                <div className="flex items-start justify-between">
                  <div className="flex items-start space-x-3">
                    <MegaphoneIcon className="h-6 w-6 text-primary-600" />
                    <div>
                      <h3 className="text-lg font-medium text-gray-900">{announcement.title}</h3>
                      <p className="mt-1 text-sm text-gray-600">
                        发布于 {formatDate(announcement.createdAt)} | 
                        {experimentId ? '' : ` 实验: ${announcement.experiment.title}`}
                      </p>
                      <div className="mt-3 text-sm text-gray-700 whitespace-pre-line">
                        {announcement.content}
                      </div>
                    </div>
                  </div>
                  
                  {canManage && isTeacherOrAdmin && (
                    <div className="flex space-x-2">
                      <Link
                        href={`/announcements/${announcement.id}/edit`}
                        className="inline-flex items-center p-1.5 border border-transparent text-xs font-medium rounded text-primary-700 hover:bg-primary-100"
                      >
                        <PencilSquareIcon className="h-4 w-4" />
                      </Link>
                      <button
                        onClick={() => handleDelete(announcement.id)}
                        className="inline-flex items-center p-1.5 border border-transparent text-xs font-medium rounded text-red-700 hover:bg-red-100"
                      >
                        <TrashIcon className="h-4 w-4" />
                      </button>
                    </div>
                  )}
                </div>
              </li>
            ))}
          </ul>
        </div>
      )}
    </div>
  )
} 